package cn.virens.database.serviceimpl;

import java.util.Collection;
import java.util.stream.Collectors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.hutool.core.date.DateUtil;
import cn.virens.database.enums.log.LogLevel;
import cn.virens.database.enums.log.LogType;
import cn.virens.database.mysql.mapper.sys.SysLogMapper;
import cn.virens.database.mysql.mapper.sys.SysRoleMapper;
import cn.virens.database.mysql.mapper.sys.SysUserMapper;
import cn.virens.database.mysql.model.sys.SysLog;
import cn.virens.web.components.shiro.ShiroAuthInterface;

@Service(ShiroAuthInterface.NAME)
public class ShiroServiceImpl implements ShiroAuthInterface {
	protected final Logger logger = LoggerFactory.getLogger(ShiroServiceImpl.class);

	private @Autowired SysLogMapper mSysLogMapper;
	private @Autowired SysUserMapper mSysUserMapper;
	private @Autowired SysRoleMapper mSysRoleMapper;

	@Override
	@Transactional(readOnly = true)
	public String login(String account) {
		return mSysUserMapper.login(account);
	}

	@Override
	@Transactional(readOnly = true)
	public Collection<String> getRoles(String account) {
		return mSysRoleMapper.getRoles(account);
	}

	@Override
	@Transactional(readOnly = true)
	public Collection<String> getResources(String account) {
		return mSysRoleMapper.getResources(account).stream().map((map) -> {
			Object identity = map.get("identity");
			Object permission = map.get("permission");

			return identity + ":" + permission;
		}).collect(Collectors.toList());
	}

	@Override
	public void onLoginSuccess(String username, String host) {
		logger.debug("用户登录成功({}):{}", username, host);

		SysLog record = new SysLog();
		record.setLevel(LogLevel.INFO.getKey());
		record.setType(LogType.LOGIN.getKey());
		record.setCreateTime(DateUtil.date());
		record.setUpdateTime(DateUtil.date());
		record.setContent("用户登录成功");
		record.setUser(username);
		record.setHost(host);

		mSysLogMapper.insertSelective(record);
	}

	@Override
	public void onLoginFailure(String username, String host) {
		logger.error("用户登录失败({}):{}", username, host);

		SysLog record = new SysLog();
		record.setLevel(LogLevel.ERROR.getKey());
		record.setType(LogType.LOGIN.getKey());
		record.setCreateTime(DateUtil.date());
		record.setUpdateTime(DateUtil.date());
		record.setContent("用户登录失败");
		record.setUser(username);
		record.setHost(host);

		mSysLogMapper.insertSelective(record);
	}
}
